package com.tc.shiro.utils;

import com.tc.cipher.PemRSAParser;
import com.tc.cipher.RSACoder;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.Cipher;
import java.security.MessageDigest;
import java.security.PrivateKey;

public class SecurityUtils {

    private static String publicKeyString="MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAKu0twRw1OimBJC5a2/p7fxd/WNHshzLtyVHO8Eqa541fOr0rQNditaYjNASoND8mZoSsuARp01w76lexGhVzT8CAwEAAQ==";

    private static String privateKeyString="MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAq7S3BHDU6KYEkLlrb+nt/F39Y0eyHMu3JUc7wSprnjV86vStA12K1piM0BKg0PyZmhKy4BGnTXDvqV7EaFXNPwIDAQABAkAJwGesfuP4moUj2wP5BSYY8RWU79tzuzYZjeQc4lXeVD+EsD9J1L8X7KreJe/qKAIDzGlKFONUkakZQ0uDX33xAiEA1QYmFs5+Kz+LK0fBhCSBN17znap5nTns5qlvuQaAhl0CIQDOWKYlQ5bQwZMsPZDvjCkcXRHNXm/pgwJWqGsSE6EwSwIgGXUaqC8VNOXrI8j3f2s9Zfia9ISi8/8wKICnMV1tjqECIAwQsuZK5W6fYvObRfY7w8ucxYW0l+aXenOGtXwBGdOxAiEAnm64vPb+7UPNkgp69ElgmC6Kvh8ljqShqoENlGilzQo=";


    public static String decryptAndDigest(String cipherText,String salt) {//cipherText 密文
        String dectyptedText = "";
        try {
            // 解密
            dectyptedText = decrypt(cipherText);
            String digestSrc = dectyptedText + salt;
            // 计算摘要
            return caclDigest(caclDigest(digestSrc));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String decrypt(String cipherText) throws Exception {
        byte[] dectyptedBytes = null;
        final Cipher cipher = Cipher.getInstance("RSA");
        PrivateKey privateKey =  PemRSAParser.getPrivateKeyFromString(privateKeyString);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        dectyptedBytes = cipher.doFinal(Base64.decodeBase64(cipherText));
        return new String(dectyptedBytes,  "UTF-8");
    }

    public static String encrypt(String sourceText){
        try {
            return Base64.encodeBase64String(RSACoder.encryptByPublicKey(sourceText.getBytes(),publicKeyString));
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    private static String caclDigest(String str) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(str.getBytes( "UTF-8"));
        String output = Hex.encodeHexString(hash);
        return output;
    }

}
